<?php

namespace Home\Controller;
use core\lib\Exception;
use Home\Org\Util\Sqlserver;
use Org\Util\UploadFile;
/**
 * 售前 售后服务
 * @author dem
 *
 */
class Boc365Controller extends HomeController {
    function db_boc365($tabname){
        return M($tabname,'tools_','DB_CONFIG_BOC365');
    }
    function orderList()
    {
        $this->display();
    }
    function getOrderlist()
    {
        $pageIndex = I('pageIndex') ? : 1;
        $pageSize = I('pageSize')?:50;
        $where= " where 1=1 ";
        $is_balance=I('is_balance');
        $order_code=I('order_code');
        $batch_no=I('batch_no');
        if( $order_code)
        {
            $where .=" and t.order_code in ( {$order_code} )";
        }
        if($batch_no)
        {
            $where .=" and t1.batch_no in ( {$batch_no} )";
        }
        if( is_numeric($is_balance) === true)
        {
            $where .=" and t.is_balance ={$is_balance}";
        }

        $sqlcount="SELECT count(*) as total FROM `tools_order` t LEFT JOIN `tools_reconcile_log` t1 ON t.`order_code`=t1.`order_code`". $where;
        $all =$this->db_boc365('order_push')->query($sqlcount);
        $start=($pageIndex-1)*$pageSize;
        $sql="SELECT t.`order_code`,FROM_UNIXTIME(t.`ctime`,'%Y-%m-%d %H:%i:%s') AS ctime,t.`is_balance`,t1.`batch_no` FROM `tools_order` t LEFT JOIN `tools_reconcile_log` t1 ON t.`order_code`=t1.`order_code`". $where." ORDER BY `order_code` limit  $start,$pageSize ";
        $list= $this->db_boc365('order_push')->query($sql);
        echo json_encode(array('total'=>$all[0]['total'],'data'=>$list));exit;
        $this->display();//`
    }
    public function exportOrderlist()
    {
        $is_balance=I('is_balance');
        $order_code=I('order_code');
        $batch_no=I('batch_no');
        $where= " where 1=1 ";
        if( $order_code)
        {
            $where .=" and t.order_code in ( {$order_code} )";
        }
        if($batch_no)
        {
            $where .=" and t1.batch_no in ( {$batch_no} )";
        }
        if( is_numeric($is_balance) === true)
        {
            $where .=" and t.is_balance ={$is_balance}";
        }
        $sqlcount="SELECT count(*) as total FROM `tools_order` t LEFT JOIN `tools_reconcile_log` t1 ON t.`order_code`=t1.`order_code`". $where;
        $all =$this->db_boc365('order_push')->query($sqlcount);
        $count=$all[0]['total'];
        if($count>50000) {
            $this->error('数据量过大。最多只能导出50000条记录！');
        }
        $sql="SELECT t.`order_code`,FROM_UNIXTIME(t.`ctime`,'%Y-%m-%d %H:%i:%s') AS ctime,case t.`is_balance` when 2 THEN '已收款' when 1 THEN '已结算'ELSE '未结算' END is_balance,t1.`batch_no` FROM `tools_order` t LEFT JOIN `tools_reconcile_log` t1 ON t.`order_code`=t1.`order_code`". $where;
        $list= $this->db_boc365('order_push')->query($sql);
        Vendor('Excel.PHPExcel');
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array( 'memoryCacheSize' => '512MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','订单号')
            ->setCellValue('B1','创建时间')
            ->setCellValue('C1','反馈时间')
            ->setCellValue('D1','结算批次');
        $i=2;                //定义一个i变量，目的是在循环输出数据是控制行数
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        foreach ($list as $key=>$v){
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $i, $v['order_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->setActiveSheetIndex(0)

                ->setCellValue("A".$i,  $v['order_code'])
                ->setCellValue("B".$i, $v['ctime'])
                ->setCellValue("C".$i, $v['p_time'])
                ->setCellValue("D".$i, $v['batch_no']);
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle('中行结算信息表');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='boc365_pushStatus'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        //header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');

    }
    function index()
    {
        $startTime= date('Y-m-15', strtotime('-1 month'));
        $endTime=date('Y-m-15');
        $this->assign('startTime',$startTime);
        $this->assign('endTime',$endTime);
        $this->display();
    }

    function getPushList()
    {
        $pageIndex = I('pageIndex') ? : 1;
        $pageSize = I('pageSize')?:50;
        $startTime=I('startTime') ? I('startTime') :date('Y-m-15', strtotime('-1 month'));
        $endTime=I('endTime') ? $endTime=I('endTime') : $endTime=date('Y-m-15');
        $is_balance=I('is_balance');
        $status=I('status');
        $where= " where 1 ";
        if($startTime)
        {
            $where .=" and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') >= '{$startTime}'";
        }

        if($endTime)
        {
            $where .=" and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') < '{$endTime}'";
        }
        if($status)
        {
            $where .=" and t1.status in ( {$status} )";
        }
        if( is_numeric($is_balance) === true)
        {
            $where .=" and t3.is_balance ={$is_balance}";
        }
        $sqlcount='SELECT count(*) as total FROM  `tools_order_push` t1  JOIN `tools_order` t3 ON  t3.`order_code`=t1.`order_code` JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status '. $where;

        $all =$this->db_boc365('order_push')->query($sqlcount);

        $start=($pageIndex-1)*$pageSize;
        $sql='SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,"%Y-%m-%d") AS p_time,t3.is_balance,t1.`batch_no` FROM  `tools_order_push` t1  JOIN `tools_order` t3 ON  t3.`order_code`=t1.`order_code` JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status '. $where. " limit  $start,$pageSize ";
        $list= $this->db_boc365('order_push')->query($sql);
        echo json_encode(array('total'=>$all[0]['total'],'data'=>$list));exit;
    }

    public function export()
    {
        set_time_limit(0);
        ini_set("memory_limit", "-1");
        $startTime=I('startTime');
        $endTime=I('endTime');
        $status=I('status');
        $where= " where 1 ";
        $is_balance=I('is_balance');
        if($startTime)
        {
            $where .=" and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') >= '{$startTime}'";
        }

        if($endTime)
        {
            $where .=" and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') < '{$endTime}'";
        }
        if($status)
        {
            $where .=" and t1.status in ( {$status})";
        }
        if( is_numeric($is_balance) === true)
        {
            $where .=" and t3.is_balance ={$is_balance}";
        }
        $sql='SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,"%Y-%m-%d") AS p_time,case t3.is_balance WHEN  1 then "已结算" when 2 then "已收款" else  "未结算" end as is_balance,t1.`batch_no` FROM  `tools_order_push` t1  JOIN `tools_order` t3 ON  t3.`order_code`=t1.`order_code` JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status '. $where;
        //echo  $sql ;exit;
        $data= $this->db_boc365('order_push')->query($sql);
        Vendor('Excel.PHPExcel');
        Vendor('Excel.PHPExcel');
        \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;  # 单元格缓存为MemoryGZip
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','订单号')
            ->setCellValue('B1','最终状态')
            ->setCellValue('C1','反馈时间')
            ->setCellValue('D1','反馈批次')
            ->setCellValue('E1','结算状态')
            //->setCellValue('E1','ceshi')
        ;
        $i=2;                //定义一个i变量，目的是在循环输出数据是控制行数
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        //print_r($data); exit;
        foreach ($data as $key=>$v){
            $batch_no=isset($v['batch_no']) ? $v['batch_no']:"";
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $i, $v['order_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->setActiveSheetIndex(0)

                ->setCellValue("A".$i,  $v['order_code'])
                ->setCellValue("B".$i, $v['status'])
                ->setCellValue("C".$i, $v['p_time'])
                ->setCellValue("D".$i, $batch_no)
                ->setCellValue("E".$i, $v['is_balance'])

            ;
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle('中行365订单状态反馈表');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='boc365_pushStatus'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        //header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }
    public function uploadReconcile()
    {
        $isBalance=I('isBalance');
        $this->assign('isBalance',$isBalance);
        $this->display('uploadReconcile');
    }
    public function uploadingReconcile()
    {
        set_time_limit(0);
        ini_set("memory_limit", "-1");
        $orderHeadArray = array(
            '订单号'=> 'order_code',
            '状态变更时间'=>'push_time',
            '订单结算所属月份'=>'batch_no'
        );
        $isBalance=I('isBalance');
        $reconcileTime='';
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {
                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream" && $theType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display('uploadSettlement');
                    return;
                }
                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;
                $objPHPExcel = \PHPExcel_IOFactory::load($filename);
                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数
                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();

                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                $ids='';
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组
                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);
                    $sql = "SELECT COUNT(*) as total FROM `tools_order_push` WHERE `order_code`='{$targetData['order_code']}' and status={$isBalance}";
                    $all = $this->db_boc365('order_push')->query($sql);
                    if ($all[0]['total'] < 1){
                        $targetData['order_code'] = addslashes($targetData['order_code']);
                        $targetData['push_time'] =  strtotime($targetData['push_time']);
                        $targetData['ctime'] = time();
                        $targetData['batch_no'] =  trim($targetData['batch_no']);
                        $targetData['is_balance'] =  trim($isBalance);
                        $str = "'" . implode("','", $targetData) . "'";
                        $ids.="'".$targetData['order_code']."',";
                        $countNum++;

                    }

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                }
                $ids= rtrim($ids, ',');

                try {
                        $sql = " insert into tools_reconcile_log (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                        $Model = $this->db_boc365('reconcile_log');
                        $result = $Model->execute($sql);
                        $query="update tools_order set is_balance={$isBalance} where order_code in($ids)";
                        $Model->execute($query);
                }catch(Exception $e)
                {

                    echo $e->getMessage();
                    exit;
                }
                $errorStr = '导入不成功！';
                if ($result) {
                    $this->success('导入成功！',U('boc365/difforders'));
                    exit;
                }
                $this->assign('errorInfo',$errorStr);
                $this->display('uploadReconcile');

            }
        }
    }

    /**比较对账文件的差异**/
    public function difforders()
    {
        $reconcileTime=I('reconcileTime') ? trim(I('reconcileTime')) : '';
        $this->assign('reconcileTime',$reconcileTime);
        if($reconcileTime=="")
        {
            $this->assign('errorInfo',"对账月份为空");
            $this->display('difforders');
            exit;
        }
        $Month=substr($reconcileTime, -2);
        $endTime=date('Y-'.$Month.'-15');
        $startTime=date("Y-m-15", strtotime("-1 month",strtotime($endTime)));
        $boc_orders=$this->db_boc365('reconcile_log')->where("batch_no='".$reconcileTime."'")->order( "push_time asc")->select();
        $boc_orders_reconcile=array();
        $pushOrders=array();
        foreach ($boc_orders as $v) {
            $v['push_time'] = date("Y-m-d", $v['push_time']);
            $v['ctime'] = date("Y-m-d", $v['ctime']);
            $boc_orders_reconcile[$v['order_code']]=$v;

        }
        if(count($boc_orders_reconcile)<1)
        {
            $this->assign('errorInfo',"没有导入中行的对账文件");
            $this->display('difforders');
            exit;

        }
        $where= " WHERE  t3.`is_balance`=0 and t1.status IN(40,65) and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') >= '{$startTime}' and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') <'{$endTime}'";
        $sql='SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,"%Y-%m-%d") AS p_time FROM  `tools_order_push` t1  JOIN `tools_order` t3 ON  t3.`order_code`=t1.`order_code` JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status  '. $where;
        $list= $this->db_boc365('order_push')->query($sql);
        foreach ($list as $value) {
            $pushOrders[$value['order_code']]=$value;
        }
        $arr=array_diff_key($boc_orders_reconcile,$pushOrders);
        $ids_array=array_keys($arr) ;
        $ids=  implode(",",  $ids_array);
        $query="SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,\"%Y-%m-%d\") as p_time FROM  `tools_order_push` t1  JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status where t1.order_code in (". $ids.")";
        $array=$this->db_boc365('order_push')->query($query);
        foreach($array as $key=>$val)
        {
            $arr[$val['order_code']]['p_time']=$val['p_time'];
            $arr[$val['order_code']]['status']=$val['status'];
        }

        $arr1=array_diff_key($pushOrders,$boc_orders_reconcile);
        foreach($arr1 as $k=>$val)
        {
            $arr[$val['order_code']]['order_code']=$val['order_code'];
            $arr[$val['order_code']]['p_time']=$val['p_time'];
            $arr[$val['order_code']]['status']=$val['status'];
        }

        if(count($arr)<1)
        {
            $this->assign('errorInfo',"没有对账异常数据");
            $this->display('difforders');
            exit;
        }
        $this->assign('arr',$arr);
        $this->assign('reconcileTime',$reconcileTime);
        $this->display('difforders');

    }
    public function exportdifforders()
    {
        $reconcileTime=I('reconcileTime');
        $Month=substr($reconcileTime, -2);
        $endTime=date('Y-'.$Month.'-15');
        $startTime=date("Y-m-15", strtotime("-1 month",strtotime($endTime)));
        $boc_orders=$this->db_boc365('reconcile_log')->where("batch_no='".$reconcileTime."'")->order( "push_time asc")->select();
        $boc_orders_reconcile=array();
        $pushOrders=array();
        foreach ($boc_orders as $v) {
            $v['push_time'] = date("Y-m-d", $v['push_time']);
            $v['ctime'] = date("Y-m-d", $v['ctime']);
            $boc_orders_reconcile[$v['order_code']]=$v;

        }

        $where= " where t1.status IN(40,65) and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') >= '{$startTime}' and FROM_UNIXTIME(t1.ctime,'%Y-%m-%d') <'{$endTime}'";

        $sql="SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,\"%Y-%m-%d\") as p_time FROM  `tools_order_push` t1  JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status ". $where;
        //echo $sql;exit;
        $list= $this->db_boc365('order_push')->query($sql);
        foreach ($list as $value) {
            $pushOrders[$value['order_code']]=$value;

        }
        $arr=array_diff_key($boc_orders_reconcile,$pushOrders);
        $ids_array=array_keys($arr) ;
        $ids=  implode(",",  $ids_array);
        $query="SELECT  t1.order_code,t1.status,FROM_UNIXTIME(t1.ctime,\"%Y-%m-%d\") as p_time FROM  `tools_order_push` t1  JOIN ( SELECT MAX(`status`) AS STATUS ,`order_code` FROM `tools_order_push`  GROUP BY `order_code`) t2 ON  t1.order_code=t2.order_code AND t1.status=t2.status where t1.order_code in (". $ids.")";
        $array=$this->db_boc365('order_push')->query($query);
        foreach($array as $key=>$val)
        {
            $arr[$val['order_code']]['p_time']=$val['p_time'];
            $arr[$val['order_code']]['status']=$val['status'];
        }
        $arr1=array_diff_key($pushOrders,$boc_orders_reconcile);
        foreach($arr1 as $k=>$val)
        {
            $arr[$val['order_code']]['order_code']=$val['order_code'];
            $arr[$val['order_code']]['p_time']=$val['p_time'];
            $arr[$val['order_code']]['status']=$val['status'];
        }
        Vendor('Excel.PHPExcel');
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array( 'memoryCacheSize' => '512MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','订单号')
            ->setCellValue('B1','中银接收结算状态时间')
            ->setCellValue('C1','结算月份')
            ->setCellValue('D1','系统反馈时间')
            ->setCellValue('E1','系统最终状态');
        $i=2;                //定义一个i变量，目的是在循环输出数据是控制行数
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        foreach ($arr as $key=>$v){
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A' . $i, $v['order_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->setActiveSheetIndex(0)

                ->setCellValue("A".$i,  $v['order_code'])
                ->setCellValue("B".$i, $v['push_time'])
                ->setCellValue("C".$i, $v['batch_no'])
                ->setCellValue("D".$i, $v['p_time'])
                ->setCellValue("E".$i, $v['status']);
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle("中行订单结算".$reconcileTime."异常订单表");
        $objPHPExcel->setActiveSheetIndex(0);
        $filename='boc365_Reconcile'. $reconcileTime;
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');

    }
    public function handorder()
    {
        $this->display();
    }
    public function handorderlist()
    {

        $pageIndex = I('pageIndex') ? : 1;
        $pageSize = I('pageSize')?:50;
        $order_code=I('order_code');
        $startTime=I('startTime');
        $endTime=I('endTime');
        $where=' 1 ';
        if($order_code){
            $where.= " and order_code='". trim($order_code) . "'";
        }
        if($startTime)
        {
            $where .=" and FROM_UNIXTIME(ctime,'%Y-%m-%d') >= '{$startTime}'";
        }

        if($endTime)
        {
            $where .=" and FROM_UNIXTIME(ctime,'%Y-%m-%d') < '{$endTime}'";
        }
        $count=$this->db_boc365('hand_order_push')->where($where)->count();
        $list= $this->db_boc365('hand_order_push')->where($where)->order(" id asc ")->limit(($pageIndex-1)*$pageSize,$pageSize)->select();
        foreach($list as $key=>$value)
        {
            $list[$key]['ctime']=date("Y-m-d H:i:s",$value['ctime']);
        }
        echo json_encode(array('total'=>$count,'data'=>$list));exit;
    }

    public function addExpOrder()
    {
        $id=I("id") ? I ("id") : 0;
        if($id>0)
        {
            $order_info=$this->db_boc365('hand_order_push')->where('id="'.$id.'"')->find();
            $this->assign('order_info',$order_info);
        }
        $this->display();
    }

    public function addingExpOrder()
    {
        $result=array('msg'=>'','state'=>200);
        $order_code=trim(I('order_code'));
        $status=I('status') ? trim(I('status')) :65;
        $id=I("id") ? I ("id") : 0;
        $remark=trim(I("remark"));
        $this->db_boc365('hand_order_push')->startTrans();
        //$this->db_boc365('order')->where('order_code="'.$order_code.'"')->save(array('status'=>0));
        $data=array('order_code'=>$order_code,'status'=>$status,'remark'=>$remark,'ctime'=>time());
       try{
           if($id>0)
           {
               $handInfo=$this->db_boc365('hand_order_push')->where('id="'.$id.'"')->find();
               $this->db_boc365('hand_order_push')->where('id="'.$id.'"')->save($data);
               $result['msg']="更新成功";
               $log=array(
                  'order_code'=>$order_code,
                   'type'=>'update',
                   'prev_status'=>$handInfo['status'],
                   'status'=>$status,
                   'cname'=>session('emp_no')
               );
               $this->db_boc365('hand_log')->add($log);

           }else{

              $this->db_boc365('hand_order_push')->add($data);
              $log=array(
                   'order_code'=>$order_code,
                   'type'=>'insert',
                   'prev_status'=>'',
                   'status'=>$status,
                   'cname'=>session('emp_no')
               );
               $this->db_boc365('hand_log')->add($log);
              $result['msg']="添加成功";
           }
           $this->db_boc365('order')->where('order_code="'.$data['order_code'].'"')->save(array('status'=>0));
           $this->db_boc365('hand_order_push')->commit();
          // $order_code
            //$this->success('导入成功！',U('boc365/handorderlist'));

        }catch(Exception $e)
        {
            $result['state']=201;
            $result['msg']="添加失败";
            $this->db_boc365('hand_order_push')->rollback();
            //$this->error('导入失败，原因：！'.$e->getMessage(),U('boc365/handorderlist'));
        }
        echo json_encode($result);exit;
    }

    public function exportOrder()
    {
        import("@.ORG.UploadFile");
        $config = array(
            'allowExts' => array('xlsx', 'xls'),
            'savePath' => './exceltojh/',
            'saveRule' => 'time',
        );
        $upload = new UploadFile($config);
        if (!$upload->upload($config['savePath'])) {
            //$this->error($upload->getErrorMsg());
            $this->error('导入失败！原因：'.$this->error($upload->getErrorMsg()), U('boc365/difforders'));
            exit;
        } else {
            $info = $upload->getUploadFileInfo();
            $theType = $info[0]['type'];
            if ($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream" && $theType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
                //var_dump($theType);die();
                $this->assign('errorInfo', "文件类型错误！");
                //$this->display('updatestockofboc365byexcel');
                //return;
                $this->error('文件类型错误', U('boc365/handorder'));
                exit;
            }

            $name = $info[0]['savename'];

            Vendor('Excel.PHPExcel');
            $filename = $config['savePath'] . $name;

            $objPHPExcel = \PHPExcel_IOFactory::load($filename);

            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
            $data = array();
            $countNum = 0;
            $mergeStr = '';
            for ($i = 2; $i <= count($sheetData); $i++) {
                //$targetData = array();
                $data['order_code'] = !empty($sheetData[$i]["A"]) ? trim($sheetData[$i]["A"]) : "";
                $data['ctime'] = time();
                $str = "'" . implode("','", $data) . "'";
                $countNum++;
                if ($countNum == 1) $mergeStr .= "({$str})";
                else $mergeStr .= ", ({$str})";

            }

            try {
                $sql = " insert into tools_hand_order_push (" . implode(',', array_keys($data)) . ") values $mergeStr";
                $this->db_boc365('hand_order_push')->execute($sql);
                $this->success('导入成功！', U('boc365/handorder'));
                exit;

            } catch (Exception $e) {

                //echo $e->getMessage();
                $this->error('导入失败！原因：'.$e->getMessage(), U('boc365/handorder'));
                exit;
            }

        }
    }

    public function editingboc365orderstatus()
    {

        $list=array();
        $model = $this->db_boc365('order_push');
        $order_code=I('order_sn');
        $where="1";
        if($order_code){
            $where.= " and order_code='". trim($order_code) . "'";
            $list =$model->where($where)->order(" `status` asc")->select();
        }
        $statusList=array(30,65,70);
        //print_r($list);exit;
        $this->assign('datas',$list);
        $this->assign('statusList',$statusList);
        if(IS_AJAX){
            $this->display('editingboc365orderstatus');
        }else{
            $this->display();
        }
    }

    public function getboc365orderstatusList()
    {
        //echo 9999;exit;
        $model = $this->db_boc365('order_push');
        $order_code=I('order_code');
        $where="1";
        if($order_code){
            $where.= " and order_code='". trim($order_code) . "'";
        }
        $list =$model->where($where)->order(" status asc")->select();

        $statusList=array(30,65,70);
        $this->assign('data',$list);
        $this->assign('statusList',$statusList);
        if(IS_AJAX){
            $this->display('editingboc365orderstatus');
        }else{
            $this->display();
        }
        //$this->display();
    }
}